<template>
  <div class="communicatePage">
    <div class="left">
      <div class="list" ref="chatWindow">
        <!-- 默认数据 -->
        <div class="list-item">
          <div class="tiem_stamp">{{ ai_time }}</div>
          <div class="robot">
            <img src="@/assets/ai_model/tel_person.png" class="avatar" />
            <div class="robot_box" style="padding-bottom: 1.85vh">
              Hi，初次见面，我是您的智能助手，您可以通过下方文字输入，或者通过语音输入，提出您的问题，我会理解您的意图，提供您满意的答案。
            </div>
          </div>
        </div>
        <!-- 对话列表 -->
        <div class="list-item" v-for="(item, index) in messages" :key="index">
          <div class="tiem_stamp" v-if="item.isUser">{{ item.currentTime }}</div>
          <div class="user" v-if="item.isUser">
            <div class="user_box">{{ item.text }}</div>
            <img src="@/assets/ai_model/self.png" class="avatar" />
          </div>
          <div class="robot" v-if="!item.isUser">
            <img src="@/assets/ai_model/tel_person.png" class="avatar" />
            <div>
              <div class="robot_box">
                <span>{{ item.text }}</span>
                <div class="recommend">
                  <div class="recommend_title" v-if="item.recommend.length > 0">相关推荐：</div>
                  <div class="recommend_list">
                    <div class="recommend_item" v-for="(child, index) in item.recommend" :key="index">
                      <div class="content">{{ child }}</div>
                      <div class="question" @click="commonSent(child)">
                        <span>去提问</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="more" v-if="item.isLoad">
                <div class="re_answer" @click="reply(item.question)">
                  <img src="@/assets/ai_model/refresh.png" />
                  <span>重新回答</span>
                </div>
                <div class="download" @click="downloadFile(item)">
                  <img src="@/assets/ai_model/download.png" />
                  <span>下载</span>
                </div>
                <div class="like" v-if="item.like === 0">
                  <img src="@/assets/ai_model/Like.png" @click="setLike(item, 1)" />
                  <div class="split"></div>
                  <img src="@/assets/ai_model/Unlike.png" @click="setLike(item, 2)" />
                </div>
                <div class="like" v-else-if="item.like === 1">
                  <img src="@/assets/ai_model/Like_select.png" @click="setLike(item, 0)" />
                  <div class="split"></div>
                  <img src="@/assets/ai_model/Unlike.png" @click="setLike(item, 2)" />
                </div>
                <div class="like" v-else>
                  <img src="@/assets/ai_model/Like.png" @click="setLike(item, 1)" />
                  <div class="split"></div>
                  <img src="@/assets/ai_model/Unlike_select.png" @click="setLike(item, 2)" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 发送对话 -->
      <div class="you_say">
        <div class="clear" @click="clearMessage">
          <img src="@/assets/ai_model/clear.png" />
        </div>
        <input v-model="newMessage" @keydown.enter="sendMessage" placeholder="您可以提问任何问题" />
        <div class="send">
          <img @click="voiceInput" src="@/assets/ai_model/voice.png" />
          <div class="bt" @click="sendMessage">发送</div>
        </div>
      </div>
    </div>
    <div class="right">
      <div class="common_title">常见问题</div>
      <div class="common_content">
        <div class="commom_list" v-for="(item, index) in commonLists" :key="index">
          <div class="list_title">
            <img src="@/assets/ai_model/dot.png" />
            <span>
              {{ item.title }}
            </span>
          </div>
          <div v-for="child in item.list" :key="child.id" style="margin-top: 0.92vh">
            <span class="item" :class="{ select: child.selcted }" @click="selectCommon(child)">
              {{ child.text }}
            </span>
          </div>
        </div>
      </div>
    </div>
    <div class="footer" v-if="showListen">
      <img class="voice_select" src="@/assets/ai_model/voice_select.gif" />
      <div class="footer_text">
        <span v-if="isShowTest">{{ resultText }}</span>
        <span v-else>想问什么，说来听听…</span>
      </div>
      <img class="close" @click="showListen = false" src="@/assets/ai_model/close.png" />
    </div>
    <VoiceToText v-if="showListen" ref="voiceToText" @voiceEnd="voiceEnd" />
  </div>
</template>

<script>
//生成唯一id
import { v4 as uuidv4 } from 'uuid'
import VoiceToText from './voiceToText.vue'
import { saveAs } from 'file-saver'

const requestUrl = '/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token='
export default {
  components: {
    VoiceToText,
  },
  props: {
    access_token: {
      type: String, // 定义数据类型
      required: true, // 可选项，表示这个 prop 是必须的
    },
  },
  data() {
    return {
      isShowTest: false,
      showListen: false,
      resultText: '',
      ai_message: '',
      ai_time: '',
      messages: [
        // { id: uuidv4(), text: '什么是数据？', isUser: true },
        // {
        //   id: uuidv4(),
        //   question: '什么是数据',
        //   text: '客服回复:你的问题是:什么是数据数据是指对客观事件进行记录、分类、计算、数据是指对客观事件进行记录、分类、计算、数据是指对客观事件进行记录、分类、计算、数据是指对客观事件进行记录、分类、计算、数据是指对客观事件进行记录、分类、计算、数据是指对客观事件进行记录、分类、计算、数据是指对客观事件进行记录、分类、计算、?',
        //   isUser: false,
        //   recommend: ['大数据与数据之间的区别', '数据与数字的差别有哪些', '怎么才算真正的理解数据的含义概念'],
        //   like: 0, //0：没有选择，1：喜欢，2：不喜欢
        // },
      ],
      newMessage: '',
      lastMessage: '', //记录上一次的提问
      commonLists: [
        {
          title: '路况预测管控推荐',
          list: [
            {
              id: uuidv4(),
              text: '短时路况预测 ',
              selcted: false,
            },
            {
              id: uuidv4(),
              text: '节假日路况预测',
              selcted: false,
            },
            {
              id: uuidv4(),
              text: '管理措施推 ',
              selcted: false,
            },
          ],
        },
        {
          title: '交通政策法规咨询',
          list: [
            {
              id: uuidv4(),
              text: '道路养护报告',
              selcted: false,
            },
            {
              id: uuidv4(),
              text: '交通事故报告',
              selcted: false,
            },
            {
              id: uuidv4(),
              text: '交通专题报告',
              selcted: false,
            },
          ],
        },
        {
          title: '日常管理文件生成',
          list: [
            {
              id: uuidv4(),
              text: '宏观政策咨询',
              selcted: false,
            },
            {
              id: uuidv4(),
              text: '地方政策咨询',
              selcted: false,
            },
          ],
        },
      ],
    }
  },
  computed: {},
  watch: {},
  methods: {
    async getBaiduData(meaagae) {
      let query = {
        messages: [
          {
            role: 'user',
            content: meaagae,
          },
        ],
      }
      const response = await this.$axios.post(requestUrl + this.access_token, query)
      return response.data.result
    },
    //文件下载
    downloadFile(item) {
      const file = new File([item.text], `${item.question}.txt`, { type: 'text/plain;charset=utf-8' })
      saveAs(file)
    },
    voiceInput() {
      this.showListen = true
      this.$nextTick(() => {
        this.$refs.voiceToText.btnControl()
      })
    },
    voiceEnd(message) {
      this.isShowTest = true
      this.resultText = message
      setTimeout(() => {
        this.newMessage = message
        this.showListen = false
        this.isShowTest = false
      }, 500)
    },
    //公共问题
    commonSent(message, commonFlag = false) {
      const now = new Date()
      const time = this.formatDateToTime(now)
      this.lastMessage = message
      this.messages.push({ id: uuidv4(), text: message, isUser: true, currentTime: time })
      this.getData(message, true, commonFlag)
    },
    //清空消息
    clearMessage() {
      this.newMessage = ''
    },
    //发送消息
    sendMessage() {
      if (this.newMessage) {
        const now = new Date()
        const time = this.formatDateToTime(now)
        this.messages.push({ id: uuidv4(), text: this.newMessage, isUser: true, currentTime: time })
        this.getData(this.newMessage)
      }
    },
    scrollToBottom() {
      const chatWindow = this.$refs.chatWindow
      chatWindow.scrollTop = chatWindow.scrollHeight
    },
    async getData(message, isFirst = false, commonFlag = false) {
      // const chatbotResponse = '客服回复:你的问题是 ' + message + '  '
      this.messages.push({
        id: uuidv4(),
        question: message,
        text: '正在思考，请稍等...',
        isUser: false,
        recommend: [],
        like: 0,
        isLoad: false,
      })
      const chatbotResponse = await this.getBaiduData(message)
      const recommend = ['大数据与数据之间的区别', '数据与数字的差别有哪些', '怎么才算真正的理解数据的含义概念']
      // 模拟客服回复
      let index = 0
      let length = this.messages.length - 1
      this.$set(this.messages[length], 'text', '')
      const typingInterval = setInterval(() => {
        if (index < chatbotResponse.length) {
          this.$set(this.messages[length], 'text', this.messages[length].text + chatbotResponse[index])
          index++
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        } else {
          clearInterval(typingInterval)
          this.pushCommom(length, recommend, commonFlag)
        }
      }, 20)

      if (!isFirst) {
        this.lastMessage = this.newMessage
        this.newMessage = ''
      }
    },
    //间隔录入推荐
    pushCommom(len, array, commonFlag = false) {
      let num = 1
      let length = array.length
      const arrayInterval = setInterval(() => {
        if (num <= length) {
          this.$set(this.messages[len], 'recommend', array.slice(0, num))
          num++
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        } else {
          clearInterval(arrayInterval)
          this.$set(this.messages[len], 'isLoad', true)
          this.setCommonListempty()
          this.$nextTick(() => {
            this.scrollToBottom()
          })
          if (commonFlag) {
            this.cancelCommon() //取消推荐选中
          }
        }
      }, 200)
    },
    //选中喜欢
    setLike(currentItem, value) {
      this.messages = this.messages.map(item => {
        if (item.id === currentItem.id) {
          item.like = value
        }
        return item
      })
    },
    //推荐选中
    selectCommon(currentChild) {
      this.commonLists = this.commonLists.map(item => {
        item.list = item.list.map(child => {
          if (child.id === currentChild.id) {
            child.selcted = true
          } else {
            child.selcted = false
          }
          return child
        })
        return item
      })
      this.commonSent(currentChild.text, true)
      this.$forceUpdate()
    },
    //推荐取消选中
    cancelCommon() {
      this.commonLists = this.commonLists.map(item => {
        item.list = item.list.map(child => {
          child.selcted = false
          return child
        })
        return item
      })
      this.$forceUpdate()
    },
    //设置前几个推荐为空
    setCommonListempty() {
      let len = this.messages.length - 1
      for (let i = 0; i < len; i++) {
        if (!this.messages[i].isUser) {
          this.$set(this.messages[i], 'recommend', [])
        }
      }
    },
    init() {
      console.log("init",this.ai_message);
      const now = new Date()
      const time = this.formatDateToTime(now)
      this.messages.push({ id: uuidv4(), text: this.ai_message, isUser: true, currentTime: time })
      this.getData(this.ai_message, true)
    },
    reply(question) {
      this.getData(question, true)
    },
    // 格式化时间-时分
    formatDateToTime(date) {
      const h = date.getHours()
      const m = date.getMinutes()
      return `${h > 9 ? h : `0${h}`}:${m > 9 ? m : `0${m}`}`
    },
  },
  created() {
    console.log("access_token",this.access_token);
    this.ai_message = localStorage.getItem('ai_message')
    this.ai_time = localStorage.getItem('ai_time')
    this.lastMessage = this.ai_message
    this.init()
  },
  mounted() {},
}
</script>
<style scoped lang="less">
.communicatePage {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 4;
  display: flex;
  .left {
    width: 74%;
    padding: 2.77vh 0 3.61vh 2.77vh;
    height: 100%;
    .list {
      height: 92%;
      overflow-y: auto;
      padding-right: 2.6vw;
      .list-item {
        margin-bottom: 2.68vh;
        .tiem_stamp {
          text-align: center;
          font-size: 18px;
          font-family: MiSans-Regular, MiSans;
          font-weight: 400;
          color: #666666;
          margin-bottom: 1.302vw;
        }
        .user {
          display: flex;
          justify-content: flex-end;
          margin-bottom: 2.314vh;
          .avatar {
            width: 3.125vw;
            height: 3.125vw;
          }
          .user_box {
            font-size: 16px;
            font-family: MicrosoftYaHei;
            color: #ffffff;
            background: linear-gradient(180deg, #003d89 0%, #0072ee 100%);
            box-shadow: 0px -1px 4px 0px rgba(56, 131, 210, 0.5);
            border-radius: 8px 36px 36px 36px;
            padding: 1.85vh 1.56vw 1.85vh 1.56vw;
            margin-right: 1.04vw;
            margin-left: 4.165vw;
          }
        }
        .robot {
          display: flex;
          .avatar {
            width: 3.125vw;
            height: 3.125vw;
            margin-right: 1.04vw;
          }
          .robot_box {
            background: #ffffff;
            box-shadow: 1px 1px 6px 0px rgba(55, 82, 170, 0.1);
            border-radius: 8px 36px 36px 36px;
            border: 2px solid #ffffff;
            padding: 1.85vh 1.56vw 0 1.56vw;
            font-size: 16px;
            font-family: MicrosoftYaHei;
            color: #333333;
            margin-right: 4.165vw;
            .recommend {
              padding-top: 1.38vh;
              .recommend_title {
                font-size: 1.67vh;
                font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
                font-weight: bold;
                color: #333333;
                background: linear-gradient(180deg, #0072ee 0%, #003d89 100%);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                margin-bottom: 1.574vh;
              }
              .recommend_list {
                display: flex;
                flex-wrap: wrap;
                justify-content: space-between;
                .recommend_item {
                  position: relative;
                  width: 13.4vw;
                  height: 11.11vh;
                  background: #f2f8ff;
                  border-radius: 0.4167vw;
                  margin-bottom: 1.85vh;
                  padding: 0.7813vw;
                  margin-right: 2.6042vw;
                  &:nth-child(3n + 3) {
                    margin-right: 0;
                  }
                  .content {
                    font-size: 1.48vh;
                    font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
                    font-weight: bold;
                    color: #333333;
                  }
                  .question {
                    position: absolute;
                    right: 0.7813vw;
                    bottom: 0.7813vw;
                    width: 3.38vw;
                    height: 2.78vh;
                    background: #d4e8ff;
                    border-radius: 2.3958vw;
                    text-align: center;
                    cursor: pointer;
                    span {
                      font-size: 14px;
                      font-family: MicrosoftYaHei;
                      color: #ffffff;
                      line-height: 14px;
                      background: linear-gradient(180deg, #0072ee 0%, #003d89 100%);
                      -webkit-background-clip: text;
                      -webkit-text-fill-color: transparent;
                    }
                  }
                }
              }
            }
          }
          .more {
            position: relative;
            display: flex;
            margin-top: 1.38vh;
            font-size: 1.48vh;
            font-family: MicrosoftYaHei;
            color: #333333;
            margin-right: 4.165vw;
            .re_answer {
              cursor: pointer;
              width: 7.3958vw;
              height: 4.44vh;
              background: #ffffff;
              box-shadow: 1px 1px 6px 0px rgba(55, 82, 170, 0.1);
              border-radius: 28px;
              border: 2px solid #ffffff;
              padding: 1.29vh 1.25vw 1.29vh 1.25vw;
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-right: 0.7813vw;
              img {
                cursor: pointer;
                width: 0.9375vw;
                height: 0.9375vw;
              }
            }
            .download {
              cursor: pointer;
              width: 5.7292vw;
              height: 4.44vh;
              background: #ffffff;
              box-shadow: 1px 1px 6px 0px rgba(55, 82, 170, 0.1);
              border-radius: 28px;
              border: 2px solid #ffffff;
              padding: 1.29vh 1.25vw 1.29vh 1.25vw;
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-right: 0.7813vw;
              img {
                width: 0.9375vw;
                height: 0.9375vw;
              }
            }
            .like {
              width: 6.5625vw;
              height: 4.44vh;
              background: #ffffff;
              box-shadow: 1px 1px 6px 0px rgba(55, 82, 170, 0.1);
              border-radius: 28px;
              border: 2px solid #ffffff;
              padding: 1.29vh 1.25vw 1.29vh 1.25vw;
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-left: auto;
              .split {
                width: 1px;
                height: 1.11vh;
                border: 1px solid #333333;
              }
              img {
                cursor: pointer;
                width: 0.9896vw;
                height: 0.9896vw;
              }
            }
          }
        }
      }
    }
    .you_say {
      width: 5100%1.4583vw;
      height: 6.667vh;
      display: flex;
      position: relative;
      .clear {
        width: 3.75vw;
        height: 3.75vw;
        background: #ffffff;
        box-shadow: 8px 8px 20px 0px rgba(55, 82, 170, 0.1);
        border-radius: 50%;
        margin-right: 1.0417vw;
        display: flex;
        align-items: center;
        justify-content: center;
        img {
          width: 2.0833vw;
          height: 2.0833vw;
          cursor: pointer;
        }
      }
      input {
        width: calc(100% - 7.4vw);
        height: 100%;
        font-size: 1.66vh;
        font-family: MicrosoftYaHei;
        color: #333333;
        padding: 0 11.04vw 0 1.25vw;
        background: #ffffff;
        border: 2px solid #ffffff;
        border-radius: 60px;
        box-shadow: 8px 8px 20px 0px rgba(55, 82, 170, 0.1);
      }
      .send {
        position: absolute;
        top: 50%;
        right: 3.2292vw;
        display: flex;
        transform: translateY(-50%);
        line-height: 5.18vh;
        align-items: center;
        img {
          width: 2.187vw;
          height: 2.187vw;
          margin-right: 1.3021vw;
          cursor: pointer;
        }
        .bt {
          cursor: pointer;
          width: 4.687vw;
          height: 5.18vh;
          background: linear-gradient(180deg, #0072ee 0%, #003d89 100%);
          box-shadow: 0px 2px 4px 0px rgba(56, 131, 210, 0.5);
          border-radius: 46px;
          text-align: center;
          line-height: 5.18vh;
          font-size: 2.22vh;
          font-family: MicrosoftYaHei;
          color: #ffffff;
        }
      }
    }
  }
  .right {
    width: 26%;
    background: rgba(246, 250, 255, 0.6);
    box-shadow: 0px 1px 10px 0px rgba(0, 0, 0, 0.06);
    border-radius: 0px 30px 30px 0px;
    backdrop-filter: blur(4px);
    padding: 1.5625vw 1.0417vw 0 1.0417vw;
    .common_title {
      font-size: 1.25vw;
      font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
      font-weight: bold;
      color: #003d89;
      height: 2.3958vw;
      padding-left: 2.1875vw;
      background: url(~@/assets/ai_model/comme_title.png) no-repeat 100% 100%;
      background-size: contain;
    }
    .common_content {
      padding: 2.314vh 0 0 1.25vw;
      .commom_list {
        margin-bottom: 2.77vh;
        &:last-child {
          margin-bottom: 0;
        }
        .list_title {
          font-size: 1.666vh;
          font-family: MicrosoftYaHei;
          color: #003d89;
          img {
            width: 0.625vw;
            height: 0.625vw;
            margin-right: 0.1563vw;
          }
        }
        .item {
          cursor: pointer;
          font-size: 1.48vh;
          font-family: MicrosoftYaHei;
          color: #333333;
          padding: 0.5vh 1.0417vw 0.5vh 1.0417vw;
        }
        .select {
          background: rgba(0, 71, 152, 0.1);
          border-radius: 15px;
        }
      }
    }
  }
  .footer {
    position: fixed;
    width: 100vw;
    height: 23.14vh;
    bottom: 0;
    left: 0;
    background: linear-gradient(180deg, #edf4fd 0%, #dfebf6 100%);
    box-shadow: 0px -2px 40px 0px rgba(0, 74, 116, 0.25);
    backdrop-filter: blur(10px);
    z-index: 6;
    .voice_select {
      position: absolute;
      top: 0;
      left: 36.5104vw;
      width: 15.625vw;
      height: 100%;
    }
    .footer_text {
      position: absolute;
      top: 50%;
      left: 51.1979vw;
      transform: translateY(-50%);
      span {
        font-size: 2.22vh;
        font-family: MicrosoftYaHei;
        color: #001a48;
      }
    }
    .close {
      cursor: pointer;
      position: absolute;
      top: 1.38vh;
      right: 0.7813vw;
      width: 1.25vw;
      height: 1.25vw;
    }
  }
}
</style>
